#include "OdpsSelectParser.h"
OdpsSelectParser::~OdpsSelectParser()
{
}

OdpsSelectParser::OdpsSelectParser(SQLExprParser_ptr theExprParser)
    : SQLSelectParser(theExprParser)
//, exprParser(theExprParser)
{
  // super(exprParser->getLexer());
  // exprParser = exprParser;
}

SQLSelectItem_ptr OdpsSelectParser::parseSelectItem()
{
  SQLExpr_ptr theExpr;
  if (*lexer->token() == Token::IDENTIFIER)
  {
    string_ptr tmp = make_string_ptr(encode_util::UnicodeToUTF8(*lexer->stringVal()));
    theExpr = SQLExpr_ptr(new SQLIdentifierExpr(tmp));
    lexer->nextTokenComma();

    if (*lexer->token() != Token::COMMA)
    {
      theExpr = this->exprParser->primaryRest(theExpr);
      theExpr = this->exprParser->exprRest(theExpr);
    }
  }
  else
  {
    theExpr = expr();
  }

  if (*lexer->token() == Token::AS)
  {
    lexer->nextToken();

    if (*lexer->token() == Token::LPAREN)
    {
      lexer->nextToken();

      OdpsUDTFSQLSelectItem_ptr selectItem = OdpsUDTFSQLSelectItem_ptr(new OdpsUDTFSQLSelectItem());

      selectItem->setExpr(theExpr);

      for (;;)
      {
        string_ptr alias = make_string_ptr(encode_util::UnicodeToUTF8(*lexer->stringVal()));
        lexer->nextToken();

        selectItem->getAliasList()->push_back(alias);

        if (*lexer->token() == Token::COMMA)
        {
          lexer->nextToken();
          continue;
        }
        break;
      }

      accept(Token::RPAREN);

      return selectItem;
    }
  }

  string_ptr alias = as();

  return SQLSelectItem_ptr(new SQLSelectItem(theExpr, alias));
}
